'use strict';
var eventEmitter = require('events');
var REDIS = require('@ym/redis');
var request = require('request');
var moment = require('moment');

var TODOLIST = require('../class/TodoList');
var SCHEDULED = require('./redis-schedule');
var tokenSchedule = new SCHEDULED({ db: 4, prefix: 'wonder_list_wechat_access' });

var accessRedis = new REDIS.promiseRedis({ db: 4, prefix: 'wonder_list_wechat_access' });

const ACCESS_TOKEN_URL = 'https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&';
const NOTIFY_URL = 'https://api.weixin.qq.com/cgi-bin/message/wxopen/template/send?access_token=';

class Wechat extends eventEmitter {
  constructor(config) {
    super();
    this.APPID = config.appid;
    this.APPSECRET = config.appsecret;

    this.TEMPLATE = 'tvjGEpC_9ywGbj9zMyIKeCROOHHFyDthenkv06kVEkM';

    this._getStoreAccessToken();
    this._scheduledAccessToken();
  }

  _scheduledAccessToken() {
    var self = this;
    tokenSchedule.onMessage(function(key) {
      if (key == 'token') {
        self._requestAccessToken();
      }
    });
  }

  _getStoreAccessToken() {
    accessRedis.get('token').then(token => {
      if (!token) {
        return this._requestAccessToken();
      }
      this.accessToken = JSON.parse(token);
    }).catch(error => console.error(error));
  }

  _requestAccessToken() {
    var self = this;
    const url = ACCESS_TOKEN_URL + `appid=${this.APPID}&secret=${this.APPSECRET}`;
    request(url, function(err, res, body) {
      if (!err) self.accessToken = JSON.parse(body);
      accessRedis.setex('token', 7000, body).catch(console.error);
    });
  }

  /**
   * 创建通知模版
   * @param {{}} params
   */
  createNotify(params) {
    var todo = params.todo;
    let template = {
      touser: params.openid,
      template_id: this.TEMPLATE,
      page: `pages/todolist/todolist?_id=${todo._id.toString()}`,
      form_id: todo.formId,
      data: {
        keyword1: {
          value: `您创建的清单 ${todo.title} 已经过去一段时间了，请注意完成情况`
        },
        keyword2: {
          value: moment(todo.create_at).format('YYYY-MM-DD HH:mm:ss')
        },
        keyword3: {
          value: moment().format('YYYY-MM-DD HH:mm:ss')
        }
      }
    };

    request(NOTIFY_URL + this.accessToken.access_token, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json'
      },
      body: JSON.stringify(template)
    }, function(err, res, body) {
      console.log(err, body);
      if (!err) TODOLIST.notified(todo._id);
    });
  }

};

var wechat = null;
/**
 * @returns {Wechat}
 */
module.exports = function() {
  if (!wechat) wechat = new Wechat(require('../config').wechat);
  return wechat;
};
